package com.thunder.ktv.scoreengine2test;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import android.content.Context;
import android.hardware.display.DisplayManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.Display;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.thunder.ktv.scoreengine2sdk.DifficultyLevel;
import com.thunder.ktv.scoreengine2sdk.ScoreDimension;
import com.thunder.ktv.scoreengine2sdk.ScoreEngine2;
import com.thunder.ktv.scoreengine2sdk.SongStyle;
import com.thunder.ktv.scoreengine2test.ui.LyricsView;
import com.thunder.ktv.scoreengine2test.ui.PitchView;
import com.thunder.ktv.scoreengine2test.ui.ScoreBarView;
import com.thunder.ktv.scoreengine2test.ui.ScoreRadarChartView;
import com.thunder.ktv.scoreengine2test.ui.ScoreView;
import com.thunder.ktv.scoreengine2test.ui.SpectrumView2;
import com.thunder.ktv.scoreengine2test.ui.WaveformView;
import com.thunder.ktv.scoreengine2test.utils.FileUtil;

import java.io.File;
import java.lang.ref.WeakReference;
import java.nio.file.ClosedFileSystemException;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 歌曲打分界面
 */
public class ScoreActivity extends AppCompatActivity {

    private static final int MSG_UPDATE_SCORE = 1;
    private static final int MSG_SHOW_ERROR = 2;
    private static final int MSG_UPDATE_WAVEFORM = 3;
    private static final int MSG_UPDATE_SPECTRUM = 4;
    private static final int INFO_FLASH_TIME = 500; //毫秒
    private static boolean showTvPresentation;

    private Song selectedSong;
    private ScoreEngineConfig configParams;
    private TextView info_text_1;
    private TextView info_text_2;
    private TextView info_text_3;
    private TextView info_text_4;
//    private TextView tvConfigInfo;
//    private TextView tvScoreInfo;
    // 帧特性显示控件
//    private TextView tvFrameFeature;
    
    // 播放器相关控件
    private SurfaceView surfaceView;
    private Button btnPlayPause;
    private Button btnSwitchTrack;
    private Button btnBack;
    private SeekBar seekBarProgress;
    private SeekBar seekBarVolume;
    private TextView tvCurrentTime;
    private TextView tvTotalTime;
    
    // 播放器实例
    private VideoPlayer videoPlayer;
    
    // 评分控制器
    private ScoreController scoreController;
    
    // 处理打分结果的Handler
    private final ScoreHandler scoreHandler = new ScoreHandler(this);
    
    // 播放状态
    private boolean isPlaying = false;
    
    // 上次分数界面刷新的时间戳（用于限流）
    private long lastScoreUpdateTime = 0;

    //显示波形图？
    boolean showWaveformView = true;

    //显示音高图？
    boolean showPitchView = true;

    //显示当前打分频谱图？
    boolean showAudioSpectrumView = true;

    //显示原唱基准频谱图？
    boolean showBaseSpectrumView = true;

    //显示打分分数折线图？
//    boolean showScoreView = true;

    boolean showLyricsView = true;

    boolean showTVScoreBarView = true;
    boolean showScoreRadarChartView = true;


    // 波形图整体面板控件
    private WaveformView waveformView;

    // 频谱图整体面板控件
    private SpectrumView2 baseSpectrumView;
    private SpectrumView2 audioSpectrumView;

    private SpectrumView2 tv_baseSpectrumView;
    private SpectrumView2 tv_audioSpectrumView;
    private PitchView pitchView;
    private PitchView tv_pitchView;
//    private ScoreView scoreView;

    private ScoreBarView tvScoreBarView;

    private ScoreRadarChartView scoreRadarChartView;

    private LyricsView lyricsView;
    private LyricsView tv_lyricsView;

    private TextView titleView;
    private TextView infoView;
    /**
     * 处理打分结果的Handler类
     */
    private static class ScoreHandler extends Handler {
        private final WeakReference<ScoreActivity> activityRef;
        
        ScoreHandler(ScoreActivity activity) {
            super(Looper.getMainLooper());
            this.activityRef = new WeakReference<>(activity);
        }
        
        @Override
        public void handleMessage(Message msg) {
            ScoreActivity activity = activityRef.get();
            if (activity == null) {
                return;
            }
            
            switch (msg.what) {
                case MSG_UPDATE_WAVEFORM:
                    activity.updateWaveformDisplay((short[]) msg.obj);
                    break;
                case MSG_UPDATE_SPECTRUM:
                    activity.updateSpectrumDisplay((float[]) msg.obj);
                    break;
                case MSG_UPDATE_SCORE:
                    activity.updateScoreDisplay((ScoreEngine2.ScoreResult) msg.obj);
                    break;
                case MSG_SHOW_ERROR:
                    activity.showError((String) msg.obj);
                    break;
            }
        }
    }

    private final Handler rateUpdateHandler = new Handler(Looper.getMainLooper());
    private Runnable rateUpdateRunnable;
    long lastTotalCallback = 0;
    private final AtomicLong totalCallback = new AtomicLong(0);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_score);
        allScore = 0;
        // 获取传递的参数
        getIntentData();
        // 初始化视图
        initViews();

        initInfoText();
        
        // 初始化播放器
        initVideoPlayer();
        
        // 初始化评分控制器
        initScoreController();
        
        // 设置播放控制监听
        setupPlaybackControl();

        initLyrics();


        // 定义每秒执行的任务
        rateUpdateRunnable = new Runnable() {
            @Override
            public void run() {
                long currentCallback = totalCallback.get();

                long bytesInLastCallback = currentCallback - lastTotalCallback;

                lastTotalCallback = currentCallback;

                // 5. 更新 UI
                if(bytesInLastCallback > 0){
                    String rateText = String.format("Rate: %d", bytesInLastCallback);
                    // 你也可以在这里使用 Log 打印到控制台
                    Log.d("DataRate", rateText);
                }

                // 6. 安排下一次在 1000 毫秒（1秒）后执行
                rateUpdateHandler.postDelayed(this, 1000);
            }
        };
        rateUpdateHandler.post(rateUpdateRunnable);
    }

    private TVPresentation tvPresentation;
    private void initPresentation() {
        DisplayManager displayManager =  (DisplayManager) this.getSystemService(Context.DISPLAY_SERVICE);
        Display[] displays = displayManager.getDisplays();
        for (Display display : displays) {
            if (display.getDisplayId() != 0) {
                tvPresentation = new TVPresentation(this, display);
                tvPresentation.show();
                surfaceView = tvPresentation.getSurfaceView();
                break;
            }
        }
    }

    private void initLyrics() {
        String lyrics = FileUtil.readString(new File(selectedSong.getLyricsFilePath()));
        if(lyricsView != null){
            lyricsView.setSongName(selectedSong.getTitle());
            lyricsView.setArtistName(selectedSong.getArtist());
            lyricsView.setLyrics(lyrics);
        }
        if(tv_lyricsView != null){
            tv_lyricsView.setSongName(selectedSong.getTitle());
            tv_lyricsView.setArtistName(selectedSong.getArtist());
            tv_lyricsView.setLyrics(lyrics);
        }
    }

    /**
     * 初始化视图
     */
    private void initViews() {
        info_text_1 = findViewById(R.id.info_text_1);
        info_text_2 = findViewById(R.id.info_text_2);
        info_text_3 = findViewById(R.id.info_text_3);
        info_text_4 = findViewById(R.id.info_text_4);

        // 初始化波形图整体面板控件
        if(showWaveformView)
            waveformView = findViewById(R.id.waveformPanelView);
        // 初始化频谱图整体面板控件
        if(showPitchView){
            pitchView = findViewById(R.id.pitch_view);
            if(tvPresentation != null){
                tv_pitchView = tvPresentation.getPitchView();
            }
        }

        if(showAudioSpectrumView){
            if(tvPresentation != null){
                tv_audioSpectrumView = tvPresentation.getAudioSpectrumView();
            }
            audioSpectrumView = findViewById(R.id.audio_spectrum);

        }
        if(showBaseSpectrumView){
            if(tvPresentation != null){
                tv_baseSpectrumView = tvPresentation.getOriginalSpectrumView();
            }
            baseSpectrumView = findViewById(R.id.base_spectrum);
        }
//        if(showScoreView)
//            scoreView = findViewById(R.id.score_view);

        if(showLyricsView){
            if(tvPresentation != null){
                tv_lyricsView = tvPresentation.getLyricsView();
            }

            lyricsView = findViewById(R.id.lyrics_view);
        }
        if(showTVScoreBarView){
            if(tvPresentation != null){
//                tvScoreBarView = tvPresentation.getScoreBarView();
            }
        }
        if(showScoreRadarChartView){
            if(tvPresentation != null){
                scoreRadarChartView = tvPresentation.getScoreRadarChartView();
                findViewById(R.id.tv_score_radar_chart_view).setVisibility(View.GONE);
            }else{
                scoreRadarChartView = findViewById(R.id.tv_score_radar_chart_view);
            }
        }
        // 初始化播放器相关控件
        if(surfaceView == null)
            surfaceView = findViewById(R.id.surfaceView);
        else{
            findViewById(R.id.surfaceView).setVisibility(View.GONE);
        }
        btnPlayPause = findViewById(R.id.btnPlayPause);
        btnSwitchTrack = findViewById(R.id.btnSwitchTrack);
        btnBack = findViewById(R.id.btnBack);
        seekBarProgress = findViewById(R.id.seekBarProgress);
        seekBarProgress.setEnabled(false);
        seekBarVolume = findViewById(R.id.seekBarVolume);
        tvCurrentTime = findViewById(R.id.tvCurrentTime);
        tvTotalTime = findViewById(R.id.tvTotalTime);
        titleView = findViewById(R.id.title_info_view);
        infoView = findViewById(R.id.info_view);
    }

    private void initInfoText() {
        if(showTvPresentation){
            titleView.setVisibility(View.GONE);
            infoView.setVisibility(View.GONE);
            return;
        }
        titleView.setText("当前播放:" + selectedSong.getTitle());
        // 1. 从数值获取难度等级枚举实例
        DifficultyLevel level = DifficultyLevel.fromValue(configParams.difficultyLevel);
        // 2. 设置文本内容
        infoView.setText("当前难度:" + level);

        int colorID = R.color.difficulty_easy;
        if(level == DifficultyLevel.NORMAL){
            colorID = R.color.difficulty_normal;
        }else if(level == DifficultyLevel.HARD){
            colorID = R.color.difficulty_hard;
        }else if(level == DifficultyLevel.EXPERT){
            colorID = R.color.difficulty_expert;
        }
        // 3. 从枚举中获取颜色资源ID，并设置颜色
        int textColor = ContextCompat.getColor(infoView.getContext(), colorID);
        infoView.setTextColor(textColor);
    }
    
    /**
     * 设置播放控制监听
     */
    private void setupPlaybackControl() {
        btnPlayPause.setOnClickListener(v -> togglePlayPause());
        btnSwitchTrack.setOnClickListener(v -> switchTrack());
        btnBack.setOnClickListener(v -> finish());
    }
    
    /**
     * 切换播放/暂停状态
     */
    private void togglePlayPause() {
        if (videoPlayer != null && scoreController != null) {
            if (isPlaying) {
                // 暂停播放和打分
                videoPlayer.pause();
                scoreController.pauseScoring();
                if(lyricsView != null)
                    lyricsView.pause();
                if(tv_lyricsView != null)
                    tv_lyricsView.pause();
            } else {
                // 开始播放和打分
                videoPlayer.start();
                scoreController.resumeScoring();
                if(lyricsView != null)
                    lyricsView.start();
                if(tv_lyricsView != null)
                    tv_lyricsView.start();
            }
            isPlaying = !isPlaying;
            updatePlayPauseButton();
        }
    }
    
    /**
     * 切换音轨
     */
    private void switchTrack() {
        if (videoPlayer != null) {
            videoPlayer.switchTrack();
        }
    }
    
    /**
     * 更新播放/暂停按钮文本
     */
    private void updatePlayPauseButton() {
        btnPlayPause.setText(isPlaying ? "暂停" : "播放");
    }
    
    /**
     * 初始化播放器
     */
    private void initVideoPlayer() {
        videoPlayer = new VideoPlayer(this, surfaceView,
                seekBarProgress, seekBarVolume,
                tvCurrentTime, tvTotalTime);

        // 设置视频路径
        if (selectedSong != null) {
            videoPlayer.setVideoPath(selectedSong.getVideoPath());
        }
    }
    
    /**
     * 获取传递的参数
     */
    private void getIntentData() {
        if (getIntent() != null) {
            // 获取showTV
            if (getIntent().hasExtra("showTV")) {
                showTvPresentation = (boolean) getIntent().getBooleanExtra("showTV",false);
                if(showTvPresentation){
                    initPresentation();
                }
            }

            // 获取歌曲信息
            if (getIntent().hasExtra("selected_song")) {
                selectedSong = (Song) getIntent().getSerializableExtra("selected_song");
                if(tvPresentation != null){
                    tvPresentation.setSelectedSong(selectedSong);
                }
                displaySongInfoAndTime();
            }
            
            // 获取配置信息
            if (getIntent().hasExtra("score_engine_config")) {
                configParams = (ScoreEngineConfig) getIntent().getSerializableExtra("score_engine_config");
                displayConfigInfo();
                if(tvPresentation != null){
                    tvPresentation.setDifficultyLevel(configParams.difficultyLevel);
                }
            }


        }
    }
    
    ScoreController.ScoreCallback scoreCallback = new ScoreController.ScoreCallback() {
        @Override
        public void onScoreResult(ScoreEngine2.ScoreResult result, short[] audioFrame, float[] spectrum) {

            totalCallback.addAndGet(1);

            Message msg = scoreHandler.obtainMessage(MSG_UPDATE_SCORE, result);
            scoreHandler.sendMessage(msg);

            Message msg2 = scoreHandler.obtainMessage(MSG_UPDATE_WAVEFORM, audioFrame);
            scoreHandler.sendMessage(msg2);

            Message msg3 = scoreHandler.obtainMessage(MSG_UPDATE_SPECTRUM, spectrum);
            scoreHandler.sendMessage(msg3);
        }

        @Override
        public void onError(String error) {
            Message msg = scoreHandler.obtainMessage(MSG_SHOW_ERROR, error);
            scoreHandler.sendMessage(msg);
        }
    };


    /**
     * 初始化评分控制器
     */
    private void initScoreController() {
        // 使用带有音频控制器的构造方法创建评分控制器
        scoreController = new ScoreController(scoreCallback, () -> {
            if(videoPlayer == null)
                return -1;
            return videoPlayer.getCurrentPosition();
        });
        
        if (selectedSong != null && configParams != null) {
            // 创建评分引擎配置
            ScoreEngine2.ScoreEngineConfig engineConfig = ScoreEngine2.ScoreEngineConfig.createDefault();
            engineConfig.style = SongStyle.fromValue(configParams.songStyle);
            engineConfig.difficulty = DifficultyLevel.fromValue(configParams.difficultyLevel);
            engineConfig.enabledDimensions = configParams.enabledDimensions;


            // 读取基准文件数据
//            byte[] baseFileData = AssetUtils.readAssetFile(this, selectedSong.getBaseFilePath());
            byte[] baseFileData = FileUtil.readBytes(selectedSong.getBaseFilePath());
//            byte[] baseFileData = FileUtil.readBytes("/sdcard/7553043_1290.base");

            if(baseFileData == null){
                Toast.makeText(this, "读取基准文件数据失败", Toast.LENGTH_SHORT).show();
                return;
            }

            // 初始化评分引擎
            boolean initSuccess = scoreController.initScoreEngine(baseFileData, engineConfig);
            if (!initSuccess) {
                Toast.makeText(this, "初始化评分引擎失败: " +
                        ScoreEngine2.getInitErrorCode().toString(), Toast.LENGTH_LONG).show();
                return;
            }

            //??
            int sentencesNum = 0;
            List<ScoreEngine2.CharEntry> charEntries = scoreController.getCharEntries();
            if(tvScoreBarView != null){
                tvScoreBarView.initCharEntries(charEntries);
                sentencesNum = tvScoreBarView.getSentences().size();
//                if(scoreRadarChartView != null){
//                    scoreRadarChartView.initMaxScore(sentencesNum * 100);
//                }
            }


            Toast.makeText(this, "评分引擎已配置", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "请先选择歌曲", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 显示歌曲信息
     */
    private void displaySongInfoAndTime() {
        if (selectedSong != null) {
            StringBuilder info = new StringBuilder();
            info.append("当前歌曲: \n");
            info.append(selectedSong.getTitle() + " - " + selectedSong.getArtist());
            info.append("\n\n");
            if(videoPlayer != null && videoPlayer.isPlaying()){
                info.append("播放器播放时间: \n").append(formatTime(videoPlayer.getCurrentPosition())).append("\n");
                info.append("打分帧数据时间: \n").append(formatTime(scoreController.getScoringBufferTime())).append("\n");
                Log.d(TAG, "displaySongInfoAndTime: video pts: " + videoPlayer.getCurrentPosition() + ",score pts: " + scoreController.getScoringBufferTime());
                Log.d(TAG, "displaySongInfoAndTime: diff pts :" + (videoPlayer.getCurrentPosition() - scoreController.getScoringBufferTime()));
            }
            if(info_text_2 != null)
               info_text_2.setText(info);
        }
    }
    
    /**
     * 显示配置信息
     */
    private void displayConfigInfo() {
//        if (configParams != null) {
//            StringBuilder sb = new StringBuilder();
//            sb.append("<打分配置> ").append("\n");
//            sb.append("歌曲风格: ").append(SongStyle.fromValue(configParams.songStyle)).append("\n");
//            sb.append("难度等级: ").append(DifficultyLevel.fromValue(configParams.difficultyLevel)).append("\n");
//            if(tvPresentation != null){
//                tvPresentation.setDifficultyLevel(configParams.difficultyLevel);
//            }
//            sb.append("评分维度: \n     ");
//            if (ScoreDimension.PITCH.isEnabled(configParams.enabledDimensions)) {
//                sb.append("音高 ");
//            }
//            if (ScoreDimension.RHYTHM.isEnabled(configParams.enabledDimensions)) {
//                sb.append("节奏 ");
//            }
//            if (ScoreDimension.BRIGHTNESS.isEnabled(configParams.enabledDimensions)) {
//                sb.append("亮度 \n     ");
//            }
//            if (ScoreDimension.EMOTION.isEnabled(configParams.enabledDimensions)) {
//                sb.append("情感 ");
//            }
//            if (ScoreDimension.BREATH.isEnabled(configParams.enabledDimensions)) {
//                sb.append("气息 ");
//            }
//            if (ScoreDimension.TIMBRE.isEnabled(configParams.enabledDimensions)) {
//                sb.append("音色 ");
//            }
//
//            info_text_2.setText(sb.toString());
//        }
    }

    /**
     * 更新波形图显示
     * @param audioFrame
     */
    private void updateWaveformDisplay(short[] audioFrame) {
        // 显示波形图
        if (waveformView != null && audioFrame != null) {
            waveformView.updateAudioData(audioFrame,null);
        }
    }

    private void updateSpectrumDisplay(float[] spectrum) {
        // 显示频谱图，将 512 长度的 spectrum 拆分为两份 256
        if (spectrum != null && spectrum.length == 512) {
            float[] original = new float[256];
            float[] audio = new float[256];
            System.arraycopy(spectrum, 0, original, 0, 256);
            System.arraycopy(spectrum, 256, audio, 0, 256);
            if (baseSpectrumView != null) {
                baseSpectrumView.updateSpectrum(original);
            }
            if (audioSpectrumView != null) {
                audioSpectrumView.updateSpectrum(audio);
            }
            if (tv_baseSpectrumView != null) {
                tv_baseSpectrumView.updateSpectrum(original);
            }
            if (tv_audioSpectrumView != null) {
                tv_audioSpectrumView.updateSpectrum(audio);
            }
        }
    }

    private static final String TAG = "ScoreActivity";

    /**
     * 更新打分显示
     */
    private  int highScoreCount = 0;
    private int allScore = 0;
    int lineIndex = 0;
    private void updateScoreDisplay(ScoreEngine2.ScoreResult result) {
        if (result != null) {
            StringBuilder sb = new StringBuilder();
            if(result.isValid()){
                sb.append("<评分分数> ").append("\n");
                allScore += result.overallScore;
                if(result.overallScore >= LyricsView.SCORE_GOOD){
                    highScoreCount++;
                }
                if(lyricsView != null){
                    lyricsView.addScoreForLine(lineIndex,result);
                }
                if(tv_lyricsView != null){
                    tv_lyricsView.addScoreForLine(lineIndex,result);
                }
                if(scoreRadarChartView != null){
                    scoreRadarChartView.addScore(result);
                }
                lineIndex++;
                Log.d(TAG, "updateScoreDisplay: " + result.overallScore);
                sb.append("高分次数: ").append(highScoreCount).append("\n");
                sb.append("整体总分: ").append(allScore).append("\n");

                if(tvPresentation != null){
//                    tvPresentation.setAllScore(allScore);
//                    tvPresentation.setHighScoreCount(highScoreCount);
//                    tvPresentation.setOverallScore(result.overallScore);
                }
                sb.append("------------------------------------\n");
                sb.append("单句总分: ").append(result.overallScore).append("\n");
                sb.append("单句音高: ").append(result.pitchScore).append("\n");
                sb.append("单句节奏: ").append(result.rhythmScore).append("\n");
                sb.append("单句亮度: ").append(result.brightnessScore).append("\n");
                sb.append("单句情感: ").append(result.emotionScore).append("\n");
                sb.append("单句气息: ").append(result.breathScore).append("\n");
                sb.append("单句音色: ").append(result.timbreScore).append("\n");
                if(info_text_3 != null)
                    info_text_3.setText(sb.toString());
//                if(scoreView != null)
//                    scoreView.updateScore(result);
            }

            int basePitch = 0;
            int resultPitch = 0;

            if (result.baseFrameFeature != null){
                basePitch = (int) result.baseFrameFeature.pitch;
            }
            if (result.frameFeature != null) {
                resultPitch = (int) result.frameFeature.pitch;
//                Log.d(TAG, "updateScoreDisplay: energy == " + result.frameFeature.energy);
                if(tvScoreBarView != null){
                    if(result.frameFeature.energy > -50){
                        tvScoreBarView.setVoicePitch(result.frameFeature.frameIndex,result.frameFeature.pitch);
                    }else{
                        tvScoreBarView.setVoicePitch(result.frameFeature.frameIndex,1);
                    }
                }
            }

            if(pitchView !=null){
                pitchView.addPatch(basePitch,resultPitch);
            }
            if(tv_pitchView != null){
                tv_pitchView.addPatch(basePitch,resultPitch);
            }

//            Log.d(TAG, "updateScoreDisplay: " + result);
//         限制刷新频率为200ms一次
            long now = System.currentTimeMillis();
            if (now - lastScoreUpdateTime < INFO_FLASH_TIME) {
                return;
            }
            displaySongInfoAndTime();
            lastScoreUpdateTime = now;

            StringBuilder baseFeatureSb = new StringBuilder();
            if (result.baseFrameFeature != null) {
                baseFeatureSb.append("<基准帧特征>\n");
                baseFeatureSb.append("帧序号: ").append(result.baseFrameFeature.frameIndex).append("\n");
                baseFeatureSb.append("VAD: ").append(result.baseFrameFeature.vadValue).append("\n");
                baseFeatureSb.append("能量: ").append(result.baseFrameFeature.energy).append("\n");
                baseFeatureSb.append("音高: ").append(result.baseFrameFeature.pitch).append("\n");
                baseFeatureSb.append("亮度: ").append(result.baseFrameFeature.brightness).append("\n");
                baseFeatureSb.append("音色: ").append(result.baseFrameFeature.timbre).append("\n");
                if(info_text_3 != null)
                    info_text_3.setText(baseFeatureSb.toString());
            }
            // 帧特性信息单独显示
            StringBuilder featureSb = new StringBuilder();
            if (result.frameFeature != null) {
                featureSb.append("<打分帧特征>\n");
                featureSb.append("帧序号: ").append(result.frameFeature.frameIndex).append("\n");
                featureSb.append("VAD: ").append(result.frameFeature.vadValue).append("\n");
                featureSb.append("能量: ").append(result.frameFeature.energy).append("\n");
                featureSb.append("音高: ").append(result.frameFeature.pitch).append("\n");
                featureSb.append("亮度: ").append(result.frameFeature.brightness).append("\n");
                featureSb.append("音色: ").append(result.frameFeature.timbre).append("\n");
                if(info_text_4 != null)
                    info_text_4.setText(featureSb.toString());
            }
        }
    }

    private String formatTime(long milliseconds) {
        long minutes = TimeUnit.MILLISECONDS.toMinutes(milliseconds);
        long seconds = TimeUnit.MILLISECONDS.toSeconds(milliseconds) % 60;
        long millis = milliseconds % 1000;
        return String.format(Locale.getDefault(), "%02d:%02d.%03d", minutes, seconds, millis);
    }
    
    /**
     * 显示错误信息
     */
    private void showError(String error) {
        Toast.makeText(this, error, Toast.LENGTH_SHORT).show();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        
        // 释放播放器资源
        if (videoPlayer != null) {
            videoPlayer.release();
            videoPlayer = null;
        }
        
        // 释放评分控制器资源
        if (scoreController != null) {
            scoreController.release();
            scoreController = null;
        }
        if(tvPresentation != null){
            tvPresentation.dismiss();
            tvPresentation = null;
        }
    }
} 